package com.atguigu.gulimall.ware.listener;

import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

//@RabbitListener必须在容器中才会生效
@Service
@RabbitListener(queues = "stock.release.stock.queue")//监听该队列
public class StockReleaseListener {

   @Autowired
    WareSkuService wareSkuService;

    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
        System.out.println("收到解锁库存的信息");
        try {
            wareSkuService.unlockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            //拒绝消息 告诉服务器消息未消费，true为重新放到队列中，让别人继续消费
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

    //根据消息类型的不同，处理不同的消息
    @RabbitHandler
    public void handleOrderCloseRelease(OrderTo to,Message message, Channel channel) throws IOException {
        System.out.println("收到订单关闭，解锁库存的信息");
        try {
            wareSkuService.unlockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            //拒绝消息 告诉服务器消息未消费，true为重新放到队列中，让别人继续消费
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

}
